/*************************************************************************
	> File Name: 004.Stack.c
	> Author: Maureen 
	> Mail: Maureen@qq.com 
	> Created Time: 五  9/ 3 12:52:42 2021
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct Stack {
    int *data;
    int capacity; //栈容量
    int top; //栈顶指针
} Stack;

/*
 * 栈的初始化
 */
Stack *init(int n) {
    Stack *sta = (Stack *)malloc(sizeof(Stack));
    sta->data = (int *)malloc(sizeof(int) * n);
    sta->capacity = n;
    sta->top = -1;
    return sta;
}

/*
 * 获取栈顶元素
 */
int top(Stack *sta) {
    return sta->data[sta->top];
}

/*
 * 判断栈是否为空
 */
int empty(Stack *sta) {
    return sta->top == -1;
}

/*
 * 入栈
 */
int push(Stack *sta, int val) {
    if (sta == NULL) return -1;
    if (sta->top == sta->capacity - 1) return -1;
    sta->data[++(sta->top)] = val;
    return 0;
}

/*
 * 出栈
 */ 
int pop(Stack *sta) {
    if (sta == NULL) return -1;
    if (empty(sta)) return -1;
    sta->top--;
    return 0;
}

/*
 * 栈内元素的打印
 */
void output(Stack *sta) {
    printf("Stack(%d) = [", sta->top + 1);
    for (int i = 0; i <= sta->top; i++) {
        i && printf(", ");
        printf("%d", sta->data[i]);
    }
    printf("]\n");
    return ;
}

/*
 * 栈的销毁
 */
void clear(Stack *sta) {
    if (sta == NULL) return ;
    free(sta->data);
    free(sta);
    return ;
}

int main() {
    srand(time(0));
    #define max_op 20 
    Stack *sta = init(max_op);
    for (int i = 0; i < max_op; i++) {
        int val = rand() % 100;
        int op = rand() % 4;
        switch (op) {
            case 0:
            case 1:
            case 2: {
                printf("push %d to the Stack, result = %d\n", val, push(sta, val));
            } break;
            case 3: {
                printf("pop %d from the Stack, result = %d\n", top(sta), pop(sta));
            } break;
        }
        output(sta), printf("\n");
    }
    #undef max_op
    clear(sta);
    return 0;
}
